package com.enation.app.javashop.core.trade.order.service.impl;

import com.enation.app.javashop.core.trade.order.model.dos.OrderMemberDO;
import com.enation.app.javashop.core.trade.order.model.dos.OrderMetaDO;
import com.enation.app.javashop.core.trade.order.model.enums.OrderMetaKeyEnum;
import com.enation.app.javashop.core.trade.order.model.enums.OrderStatusEnum;
import com.enation.app.javashop.core.trade.order.service.OrderMemberManager;
import com.enation.app.javashop.core.trade.order.service.OrderMetaManager;
import com.enation.app.javashop.framework.database.DaoSupport;
import com.enation.app.javashop.framework.redis.transactional.RedisTransactional;
import com.google.common.collect.Maps;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 会员订单状态汇总
 *
 * @author Snow create in 2018/6/27
 * @version v2.0
 * @since v7.0.0
 */
@Service
public class OrderMemberManagerImpl implements OrderMemberManager {

    @Autowired
    @Qualifier("tradeDaoSupport")
    private DaoSupport daoSupport;

    private static Map<String, String> updateFiledMap = new HashMap();

    static {
        updateFiledMap.put(OrderStatusEnum.NEW.name(), "order_new");
        updateFiledMap.put(OrderStatusEnum.PAID_OFF.name(), "order_paid_off");
        updateFiledMap.put(OrderStatusEnum.SHIPPED.name(), "order_shipped");
        updateFiledMap.put(OrderStatusEnum.ROG.name(), "order_rog");
        updateFiledMap.put(OrderStatusEnum.COMPLETE.name(), "order_completed");
        updateFiledMap.put(OrderStatusEnum.CANCELLED.name(), "order_cancelled");
        //updateFiledMap.put(OrderStatusEnum.AFTER_SERVICE.name(), "order_after_service");
        updateFiledMap.put(OrderStatusEnum.CONFIRM.name(), "order_confirm");
        updateFiledMap.put(OrderStatusEnum.INTODB_ERROR.name(), "order_error");
    }

    @Override
    public void add(OrderMemberDO orderMemberDO) {
        this.daoSupport.insert(orderMemberDO);
    }

    @Override
    public OrderMemberDO getOrderMember(int memberId) {
        String sql = "select * from es_member_order where member_id=?";
        OrderMemberDO orderMemberDO = this.daoSupport.queryForObject(sql, OrderMemberDO.class, memberId);
        return orderMemberDO;
    }

    @Override
    @Deprecated
    public void updateOrderMember(String oldFiled, String newFiled, int memberId) {

        // 查询会员订单汇总
        OrderMemberDO orderMember = getOrderMember(memberId);

        // 不存在先添加
        if (orderMember == null) {
            orderMember = new OrderMemberDO();
            orderMember.setMemberId(memberId);
            this.daoSupport.insert(orderMember);
        }

        StringBuilder sql = new StringBuilder("update es_member_order set ");
        if (oldFiled != null) {
            String minusSql = oldFiled + " =" + oldFiled + "-1";
            sql.append(minusSql);
        }
        if (oldFiled != null && newFiled != null) {
            sql.append(",");
        }
        if (newFiled != null) {
            String addSql = newFiled + " =" + newFiled + "+1";
            sql.append(addSql);
        }
        if (newFiled != null && newFiled.equals("order_rog")) {
            sql.append(",order_comment=order_comment+1");
        }
        sql.append(" where member_id = ?");
        this.daoSupport.execute(sql.toString(), memberId);
    }

    @Override
    @Transactional(value = "tradeTransactionManager",propagation = Propagation.REQUIRED,rollbackFor = {Exception.class})
    public void orderStatistic(Integer memberId) {
        // 查询会员订单汇总
        OrderMemberDO orderMember = getOrderMember(memberId);

        // 不存在先添加
        if (orderMember == null) {
            orderMember = new OrderMemberDO();
            orderMember.setMemberId(memberId);
            orderMember.setCreateTime(System.currentTimeMillis());
            this.daoSupport.insert(orderMember);
        }

        StringBuilder sql = new StringBuilder("update es_member_order set ");

        // 订单状态统计
        String sqlOrderStatus = "SELECT order_status orderStatus,COUNT( * ) count FROM es_order WHERE member_id = ? GROUP BY order_status";
        List<Map> orderStatusList = this.daoSupport.queryForList(sqlOrderStatus, memberId);
        if(!CollectionUtils.isEmpty(orderStatusList)){
            Map<String, String> hasCountField = Maps.newHashMap();
            for (Map orderStatusMap : orderStatusList) {
                String orderStatus = (String) orderStatusMap.get("orderStatus");
                long count = (long) orderStatusMap.get("count");
                String updateField = updateFiledMap.get(orderStatus);
                if (updateField == null) {
                    continue;
                }
                sql.append(updateField + "=" + count).append(",");
                hasCountField.put(orderStatus,updateField);
            }
            for (Map.Entry<String, String> updateFieldMap : updateFiledMap.entrySet()) {
                String orderStatus = updateFieldMap.getKey();
                if(!hasCountField.containsKey(orderStatus)){
                    sql.append(updateFieldMap.getValue() + "=" + 0).append(",");
                }
            }
        }

        // 评论数统计(已收货)
        String sqlOrderComment = "SELECT COUNT( * ) count FROM es_order WHERE member_id = ? and order_status='ROG' and comment_status='UNFINISHED'";
        List<Map> commentStatusList = this.daoSupport.queryForList(sqlOrderComment, memberId);
        if (!CollectionUtils.isEmpty(commentStatusList)) {
            for (Map orderCommentMap : commentStatusList) {
                long count = (long)  orderCommentMap.get("count");
                sql.append("order_comment=" + count).append(",");
            }
        }

        // 退款和售后
        String sqlOrderRefund = "SELECT COUNT( * ) count FROM  es_refund  WHERE member_id = ? ";
        List<Map> refundList = this.daoSupport.queryForList(sqlOrderRefund, memberId);
        if (!CollectionUtils.isEmpty(refundList)) {
            for (Map refundMap : refundList) {
                long count = (long)  refundMap.get("count");
                sql.append("order_after_service=" + count).append(",");
            }
        }

        sql.append("update_time=" + System.currentTimeMillis() + " ");
        sql.append(" where member_id = ?");
        this.daoSupport.execute(sql.toString(), memberId);

    }

}
